﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Logging;
using MKAdminCore.DTO.Web.Common;
using MKAdminCore.Models;
using MKAdminCore.ToolKit.Config;
using MKAdminCore.ToolKit.Extensions;
using MKAdminCore.ToolKit.FileHelper;
using MKAdminCore.ToolKit.VerifyCodeHelper;

namespace MKAdminCore.Controllers
{
    public class HomeController : BaseMvcController
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            var userInfo = base.GetUserInfo();
            return View(PageViewFilesConfig.Home, userInfo);
        }

        public IActionResult Welcome()
        {
            return View(PageViewFilesConfig.Welcome);
        }

        /// <summary>
        /// 上传文件处理
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns> [FromForm] IFormCollection formCollection
        [HttpPost]
        public async Task<IActionResult> UploadFile()
        {
            var formCollection = Request.Form;
            var files = formCollection.Files;
            long size = files.Sum(f => f.Length);

            var result = new HttpResponseResult<UploadFileModel>()
            {
                Code = (int)HttpResponseCode.BadRequest
            };
            if (files != null && files.Count > 0)
            {
                //只保存第一个文件
                var fileFirst = ((FormFileCollection)formCollection.Files)[0];

                string name = fileFirst.FileName;
                string fileExtension = Path.GetExtension(name).ToLower();
                if (Request.Form["uploadfile_ant"].Count <= 0)
                {
                    result.Msg = "请设置参数：ant, 参照web.config中 FileKit->Catalog->Key的值！";
                    return Ok(result);
                }
                var key = Request.Form["uploadfile_ant"].ToString();
                var catalogConfig = AppSettingConfigExtensions.GetUploadFileConfigInfo(key);

                if (fileFirst.Length > catalogConfig.FileSize * 1024 * 1024)
                {
                    result.Msg = $"上传文件必须小于等于 {catalogConfig.FileSize}MB";
                    return Ok(result);
                }

                //StreamReader reader = new StreamReader(fileFirst.OpenReadStream());
                //string content = reader.ReadToEnd();

                var catalog = $@"{ DateTime.Now.ToString("yyyyMM")}/{DateTime.Now.ToString("yyyyMMdd")}/{DateTime.Now.ToString("HH")}";
                string filePath = $@"{catalogConfig.SavePath}/{catalog}";
                if (!Directory.Exists(filePath))
                    Directory.CreateDirectory(filePath);

                var fileName = string.Format("{0}{1}", Guid.NewGuid().ToString("N"), fileExtension);
                filePath = $@"{filePath}/{fileName}";

                using (FileStream fs = System.IO.File.Create(filePath))
                {
                    // 复制文件
                    await fileFirst.CopyToAsync(fs);
                    // 清空缓冲区数据
                    fs.Flush();
                }
                result.Data = new UploadFileModel()
                {
                    catalog = catalog,
                    fileName = fileName,
                    fileSize = fileFirst.Length,
                    originalName = name,
                    url = $"{catalogConfig.SaveUrl}/{catalog}/{fileName}"
                };
                result.Code = (int)HttpResponseCode.Ok;
            }
            else
            {
                result.Code = (int)HttpResponseCode.BadRequest;
                result.Msg = "请选择文件";
            }
            return Ok(result);
        }

        /// <summary>
        /// 下载本地文件
        /// </summary>
        /// <param name="fileName">文件名:(eg:Files/用户信息模板.xlsx)</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> DownLoadFile(string fileName)
        {
            var directory = Environment.CurrentDirectory;

            var filePath = $@"{directory}\wwwroot\{fileName}";

            if (string.IsNullOrEmpty(filePath) || !System.IO.File.Exists(filePath))
            {
                throw new Exception("文件不存在");
            }
            var memoryStream = new MemoryStream();
            using (var stream = new FileStream(filePath, FileMode.Open))
            {
                await stream.CopyToAsync(memoryStream);
            }
            memoryStream.Seek(0, SeekOrigin.Begin);
            //文件名必须编码，否则会有特殊字符(如中文)无法在此下载。
            string encodeFilename = Path.GetFileName(fileName);
            Response.Headers.Add("Content-Disposition", "attachment; filename=" + encodeFilename);
            return new FileStreamResult(memoryStream, MimeMappingHelper.GetMimeMapping(filePath));//文件流方式，指定文件流对应的
        }

        /// <summary>
        /// 下载配置文件配置好的文件
        /// </summary>
        /// <param name="catalog"></param>
        /// <param name="fileName"></param>
        /// <param name="type">0:临时目录,1:正式目录</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> DownLoadConfigFile(string key, string catalog, string fileName)
        {
            var catalogConfig = AppSettingConfigExtensions.GetUploadFileConfigInfo(key);

            var filePath = $@"{catalogConfig.SavePath}\{catalog}\{fileName}";

            if (string.IsNullOrEmpty(filePath) || !System.IO.File.Exists(filePath))
            {
                throw new Exception("文件不存在");
            }
            var memoryStream = new MemoryStream();
            using (var stream = new FileStream(filePath, FileMode.Open))
            {
                await stream.CopyToAsync(memoryStream);
            }
            memoryStream.Seek(0, SeekOrigin.Begin);
            //文件名必须编码，否则会有特殊字符(如中文)无法在此下载。
            string encodeFilename = Path.GetFileName(fileName);
            Response.Headers.Add("Content-Disposition", "attachment; filename=" + encodeFilename);
            return new FileStreamResult(memoryStream, MimeMappingHelper.GetMimeMapping(filePath));//文件流方式，指定文件流对应的
        }

        [HttpGet]
        public IActionResult SignOut()
        {
            HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            //跳到登录页
            return Redirect("/");
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        /// <summary>
        /// 获取图形验证码
        /// </summary>
        /// <returns></returns>
        //[AllowAnonymous]   //添加匿名无效，需要排查问题
        //[HttpPost]
        //public IActionResult GetVerifyCode()
        //{
        //    string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.MixVerifyCode);
        //    var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 100, 40);
        //    MemoryStream stream = new MemoryStream();

        //    bitmap.Save(stream, ImageFormat.Jpeg);

        //    string imgCode = Convert.ToBase64String(stream.ToArray());

        //    var codeInfo = new
        //    {
        //        imgCode = imgCode
        //    };

        //    return Ok(codeInfo);
        //}
    }
}
